import { useAuthStore } from "@/store/auth";
import { message } from "antd";
import { merge } from "lodash";
import { Axios } from "./Axios";
import type { AxiosTransform, CreateAxiosOptions } from "./types";
import { CodeEnum } from "./types";
import router from "next/router";

export const WhiteListUrl = [
  '/auth/login'
]

const transform: AxiosTransform = {
  beforeRequestHook: (config, options) => {
    const { apiUrl, withToken, tokenPrefix, tokenHeaderName, headers } = options;

    // Add token to header
    if (withToken && !WhiteListUrl.includes(config.url as string)) {
      const token = useAuthStore.getState().token;
      
      config.headers = {
        [tokenHeaderName as string]: `${tokenPrefix}${token}`,
        'X-YUJIA-Principal':"%7B%22divs%22%3A%22%22%2C%22enabled%22%3Atrue%2C%22accountNonExpired%22%3Atrue%2C%22credentialsNonExpired%22%3Atrue%2C%22accountNonLocked%22%3Atrue%2C%22manageOrgId%22%3Anull%2C%22orgCode%22%3A%22%22%2C%22orgName%22%3A%22%22%2C%22jobCode%22%3A%22%22%2C%22jobId%22%3Anull%2C%22name%22%3A%22%E5%B9%B3%E5%8F%B0%E7%AE%A1%E7%90%86%E5%91%98%22%2C%22jobCodes%22%3A%22%22%2C%22roleCodes%22%3A%22'PlatformManager'%22%2C%22subject%22%3Anull%2C%22issuer%22%3Anull%2C%22audience%22%3Anull%2C%22authenticatedAt%22%3Anull%2C%22nonce%22%3Anull%2C%22authenticationContextClass%22%3Anull%2C%22authenticationMethods%22%3Anull%2C%22authorizedParty%22%3Anull%2C%22accessTokenHash%22%3Anull%2C%22authorizationCodeHash%22%3Anull%2C%22issuedAt%22%3Anull%2C%22expiresAt%22%3Anull%2C%22zoneInfo%22%3Anull%2C%22locale%22%3Anull%2C%22fullName%22%3Anull%2C%22email%22%3Anull%2C%22givenName%22%3Anull%2C%22familyName%22%3Anull%2C%22profile%22%3Anull%2C%22nickName%22%3Anull%2C%22preferredUsername%22%3Anull%2C%22picture%22%3Anull%2C%22website%22%3Anull%2C%22emailVerified%22%3Anull%2C%22gender%22%3Anull%2C%22birthdate%22%3Anull%2C%22phoneNumber%22%3Anull%2C%22phoneNumberVerified%22%3Anull%2C%22username%22%3A%22platformAdmin%22%2C%22address%22%3A%7B%22formatted%22%3Anull%2C%22streetAddress%22%3Anull%2C%22locality%22%3Anull%2C%22region%22%3Anull%2C%22postalCode%22%3Anull%2C%22country%22%3Anull%2C%22%40class%22%3A%22org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaim%22%7D%2C%22id%22%3A2%2C%22updatedAt%22%3Anull%2C%22middleName%22%3Anull%2C%22jobName%22%3A%22%22%2C%22orgId%22%3Anull%2C%22password%22%3Anull%7D",
        'x-yujia-app-id':"app1",
        'x-yujia-current-app':'{"appId":"app1","id":2}',
      }
    }
    

    // Add api prefix to url
    if (apiUrl) {
      config.url = `${apiUrl}${config.url}`;
    }

    // Merge headers
    if (headers) {
      config.headers = merge(config.headers, headers);
    }

    return config;
  },

  transformRequestHook: (res, options) => {
    const { isTransformResponse, showErrorMessage } = options;

    let _msg = "";

    const { code, message: msg } = res.data;

    if (code === CodeEnum.Success) {

    } else if (code === CodeEnum.Unauthorized) {
      _msg = msg || "Unauthorized";
    } else if (code === CodeEnum.BadRequest) {
      _msg = msg || "BadRequest";
    } else {
      _msg = msg || "error";
    }

    if(showErrorMessage) {
      message.error(_msg);
    }

    if (isTransformResponse) {
      return res.data;
    } else {
      return res;
    }
  }
};

export const createAxios = (opt?: CreateAxiosOptions) => {
  return new Axios(
    merge(
      {
        transform,
        requestOptions: {
          joinParamsToUrl: true,
          isTransformResponse: true,
          apiUrl: process.env.NEXT_PUBLIC_API_PREFIX,
          showErrorMessage: false,
          showLoading: true,
          joinTime: false,
          tokenPrefix: "Bearer ",
          tokenHeaderName: "Authorization",
          withToken: true
        }
      },
      opt || {}
    )
  );
};

export const http = createAxios();
